import React, { useState } from 'react';
import './SingleStockPage.scss';
import {
  LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer
} from 'recharts';
import { StockOutlined } from '@ant-design/icons';
import axios from 'axios';

const StockInfoTable = ({ info }) => {
  const displayFields = [
    '股票代码', '股票名称', '最新价', '涨跌幅', '涨跌额', '成交量',
    '振幅', '最高', '最低', '今开', '昨收', '市盈率', '换手率'
  ];

  const formatValue = (key, value) => {
    if (['涨跌幅', '振幅', '换手率'].includes(key)) return (value / 100).toFixed(2) + '%';
    if (['最新价', '涨跌额', '最高', '最低', '今开', '昨收'].includes(key)) return (value / 100).toFixed(2);
    if (key === '市盈率') return (value / 100).toFixed(2);
    if (key === '成交量') return (value / 10000).toFixed(2) + '万手';
    return value;
  };

  return (
    <div className="stock-info-table">
      {displayFields.map((key) => (
        <div className="info-row" key={key}>
          <span className="label">{key}</span>
          <span className="value">{formatValue(key, info[key])}</span>
        </div>
      ))}
    </div>
  );
};

const SingleStockPage = () => {
  const [stockCode, setStockCode] = useState('');
  const [stockData, setStockData] = useState(null);
  const [error, setError] = useState('');

  const fetchStockData = async () => {
    try {
      const token = localStorage.getItem('jwt_token');
      const response = await axios.post(
        '/api/ui/singlestock',
        { code: stockCode },
        {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        }
      );

      if (response.data.code === 0) {
        const { stock_info, price_curve, rate_curve } = response.data.data;

        const prices = price_curve.reverse().map(item => ({
        ...item,
        timestamp: new Date(`2025-${item.date}`).getTime()

      }));

        const rates = rate_curve.reverse().map(item => ({
          ...item,
          timestamp: new Date(`2025-${item.date}`).getTime()
        }));

        setStockData({
          info: stock_info[0],
          prices: prices,
          rates: rates
        });
        setError('');
      } else {
        setStockData(null);
        setError(response.data.message || '查询失败');
      }
    } catch (err) {
      setStockData(null);
      if (err.response && err.response.status === 401) {
        setError('未授权，请先登录');
      } else {
        setError('查询失败，请检查股票代码或网络问题');
      }
    }
  };

  const handleSearch = () => {
    if (stockCode.trim() !== '') {
      fetchStockData();
    }
  };

  const getAllTimestamps = (data) => {
    return data.map((item) => item.timestamp);
  };

  return (
    <div className="single-stock-page">
        <div className="page-header">
        <StockOutlined style={{ fontSize: '28px', color: '#1ecbe1', marginRight: '10px' }} />
        <h1>单股行情查询</h1>
      </div>
      
      <div className="search-bar">
        <input
          type="text"
          placeholder="请输入股票代码（如 300423）"
          value={stockCode}
          onChange={(e) => setStockCode(e.target.value)}
        />
        <button onClick={handleSearch}>查询</button>
      </div>

      {error && <p className="error">{error}</p>}

      {stockData && (
        <div className="stock-result">
          <h2>{stockData.info['股票名称']}（{stockData.info['股票代码']}）</h2>

          <StockInfoTable info={stockData.info} />

          <div className="charts">
            <div className="chart-box">
              <h3>近15日收盘价</h3>
              <ResponsiveContainer width="100%" height={300}>
                <LineChart data={stockData.prices}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis
                    dataKey="timestamp"
                    type="number"
                    domain={['dataMin', 'dataMax']}
                    ticks={getAllTimestamps(stockData.prices)}
                    tickFormatter={(ts) => {
                      const date = new Date(ts);
                      return `${date.getMonth() + 1}-${date.getDate()}`;
                    }}
                    //angle={-45}
                    textAnchor="end"
                  />
                  <YAxis />
                  <Tooltip
                    labelFormatter={(ts) => {
                      const date = new Date(ts);
                      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
                    }}
                    formatter={(v) => `${v.toFixed(2)} 元`}
                  />
                  <Legend />
                  <Line type="monotone" dataKey="value" name="收盘价" stroke="#8884d8" />
                </LineChart>
              </ResponsiveContainer>
            </div>

            <div className="chart-box">
              <h3>近15日涨跌幅（%）</h3>
              <ResponsiveContainer width="100%" height={300}>
                <LineChart data={stockData.rates}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis
                    dataKey="timestamp"
                    type="number"
                    domain={['dataMin', 'dataMax']}
                    ticks={getAllTimestamps(stockData.rates)}
                    tickFormatter={(ts) => {
                      const date = new Date(ts);
                      return `${date.getMonth() + 1}-${date.getDate()}`;
                    }}
                    //angle={-45}
                    textAnchor="end"
                  />
                  <YAxis />
                  <Tooltip
                    labelFormatter={(ts) => {
                      const date = new Date(ts);
                      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
                    }}
                    formatter={(v) => `${v.toFixed(2)}%`}
                  />
                  <Legend />
                  <Line type="monotone" dataKey="value" name="涨跌幅" stroke="#82ca9d" />
                </LineChart>
              </ResponsiveContainer>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default SingleStockPage;
